package com.songlanyun.modules.account.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.songlanyun.common.enums.MemberConstant;
import com.songlanyun.common.exception.RRException;
import com.songlanyun.modules.account.model.dto.UserThirdIdentityDTO;
import com.songlanyun.modules.account.service.AccountService;
import com.songlanyun.modules.exception.MemberException;
import org.apache.catalina.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songlanyun.common.utils.PageUtils;
import com.songlanyun.common.utils.Query;

import com.songlanyun.modules.account.dao.UserThirdIdentityDao;
import com.songlanyun.modules.account.entity.UserThirdIdentityEntity;
import com.songlanyun.modules.account.service.UserThirdIdentityService;


@Service("yxtUserThirdIdentityService")
public class UserThirdIdentityServiceImpl extends ServiceImpl<UserThirdIdentityDao, UserThirdIdentityEntity> implements UserThirdIdentityService {

    @Autowired
    private AccountService accountService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<UserThirdIdentityEntity> page = this.page(
                new Query<UserThirdIdentityEntity>().getPage(params),
                new QueryWrapper<UserThirdIdentityEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 是否抛错
     *
     * @param userId
     * @param isThrow
     * @return
     */
    @Override
    public UserThirdIdentityEntity getByUserId(Long userId, boolean isThrow) {
        UserThirdIdentityEntity userThirdIdentityEntity = baseMapper.selectOne(
                new LambdaQueryWrapper<UserThirdIdentityEntity>()
                        .eq(UserThirdIdentityEntity::getUserId, userId)
                        .eq(UserThirdIdentityEntity::getThirdType, MemberConstant.ThirdType.WECHAT)
        );

        if (userThirdIdentityEntity == null) {
            if (isThrow) {
                throw new RRException(MemberException.OPENID_NOT_EXISTS);
            }
        }
        return userThirdIdentityEntity;
    }

    @Override
    public String getOpenIdByUserId(Long userId, boolean isThrow) {
        UserThirdIdentityEntity userThirdIdentityEntity = getByUserId(userId, isThrow);
        if (userThirdIdentityEntity == null) {
            return null;
        }
        String identityCode = userThirdIdentityEntity.getIdentityCode();

        if (StringUtils.isBlank(identityCode)) {
            if (isThrow) {
                throw new RRException(MemberException.NOT_OPENID);
            }
        }
        return identityCode;
    }

    @Override
    public UserThirdIdentityEntity loadByThirdType(Long userId, MemberConstant.ThirdType thirdType, boolean tw) {
        UserThirdIdentityEntity one = this.lambdaQuery()
                .eq(UserThirdIdentityEntity::getUserId, userId)
                .eq(UserThirdIdentityEntity::getThirdType, thirdType)
                .last("limit 1")
                .one();
        if (ObjectUtil.isNull(one) && tw) {
            if (thirdType == MemberConstant.ThirdType.WECHAT) {
                throw new RRException(MemberException.YOU_ARE_NOT_BOUND_TO_WECHAT);
            }
            if (thirdType == MemberConstant.ThirdType.ALIPAY) {
                throw new RRException(MemberException.YOU_ARE_NOT_BOUND_TO_ALIPAY);
            }
        }
        return one;
    }

    @Override
    public void binding(Long userId, UserThirdIdentityDTO dto) {
        String identityCode = "";
        switch (dto.getThirdType()) {
            case 0://微信
                identityCode = accountService.getWechatOpenIdByCode(dto.getCode());
                break;
            case 1://支付宝
                identityCode = accountService.getAlipayUserIdByCode(dto.getCode());
                break;
            default:
                throw new RRException("第三方身份错误");
        }

        //查询该用户是否绑定过
        UserThirdIdentityEntity entity = this.loadByThirdType(userId, MemberConstant.ThirdType.getByCode(dto.getThirdType()), false);
        if (ObjectUtil.isNull(entity)) {
            entity = new UserThirdIdentityEntity();
            entity.setUserId(userId);
            entity.setThirdType(MemberConstant.ThirdType.getByCode(dto.getThirdType()));
        }
        entity.setIdentityCode(identityCode);
        this.saveOrUpdate(entity);
    }

    @Override
    public void unbind(Long userId, UserThirdIdentityDTO dto) {
        this.baseMapper.delete(
                new LambdaQueryWrapper<UserThirdIdentityEntity>()
                        .eq(UserThirdIdentityEntity::getUserId, userId)
                        .eq(UserThirdIdentityEntity::getThirdType, dto.getThirdType())
        );
    }

}
